package com.example.day1201_wlan.slice;

import com.example.day1201_wlan.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.window.dialog.ToastDialog;
import ohos.wifi.WifiDevice;
import ohos.wifi.WifiDeviceConfig;
import ohos.wifi.WifiSecurity;

public class HotConfig extends AbilitySlice {
    private String mSsid;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_hotconfig);

        initCompent();

    }

    private void initCompent() {
        Button addbtn = findComponentById(ResourceTable.Id_add_untrusted_button);
        Button removebtn = findComponentById(ResourceTable.Id_remove_untrusted_button);

        addbtn.setClickedListener(component -> addUntrust());
        removebtn.setClickedListener(component -> removeUntrust());
    }

    /**
     * 删除不信任wifi
     */
    private void removeUntrust() {

        getWifiSsid();
        if (mSsid == null) {
            new ToastDialog(getContext()).setText("未连接wifi").show();
            return;
        }

        WifiDevice instance = WifiDevice.getInstance(this);
        WifiDeviceConfig wifiDeviceConfig = new WifiDeviceConfig();
        // 设置不信任 wifi 的名称
        wifiDeviceConfig.setSsid(mSsid);
        // wifi密码
        wifiDeviceConfig.setPreSharedKey("15236227644");
        //加密模式
        wifiDeviceConfig.setSecurityType(WifiSecurity.PSK);
        // 是否隐藏 不信任wifi名称
        wifiDeviceConfig.setHiddenSsid(false);

        boolean b = instance.removeUntrustedConfig(wifiDeviceConfig);
        new ToastDialog(getContext()).setText(b?"不信任wifi"+mSsid+"移除成功":"移除失败").show();

    }
    /**
     * 增加不信任wifi
     */
    private void addUntrust() {
        getWifiSsid();
        if (mSsid == null) {
            new ToastDialog(getContext()).setText("未连接wifi").show();
            return;
        }

        WifiDevice instance = WifiDevice.getInstance(this);
        WifiDeviceConfig wifiDeviceConfig = new WifiDeviceConfig();
        // 设置不信任 wifi 的名称
        wifiDeviceConfig.setSsid(mSsid);
        // wifi密码
        wifiDeviceConfig.setPreSharedKey("15236227644");
        //加密模式
        wifiDeviceConfig.setSecurityType(WifiSecurity.PSK);
        // 是否隐藏 不信任wifi名称
        wifiDeviceConfig.setHiddenSsid(false);

        boolean b = instance.addUntrustedConfig(wifiDeviceConfig);
        new ToastDialog(getContext()).setText(b?"不信任wifi"+mSsid+"添加成功":"添加失败").show();

    }

    /**
     * 获取连接wifi ssid
     */
    private void getWifiSsid(){
        WifiDevice instance = WifiDevice.getInstance(this);
        boolean connected = instance.isConnected();
        if (!connected){
            mSsid = null;
            return;
        }
        mSsid = instance.getLinkedInfo().get().getSsid();

    }


}
